package c6;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 分区
 * partitioningBy
 * key为Boolean
 * 分区的好处在于保留了分区函数返回true或false的两套流元素列表。
 */
public class Partitioning {
    public static void main(String[] args) {
        List<Dish> menu=Dish.menu;
        //是否蔬菜分组
        Map<Boolean,List<Dish>> partitionedMenu=menu.stream()
                .collect(Collectors.partitioningBy(Dish::isVegetarian));
        System.out.println(partitionedMenu);
        //是否蔬菜分组，并且每组按照类型分开
        Map<Boolean,Map<Dish.Type,List<Dish>>> vegetarianByType=menu.stream()
                .collect(Collectors.partitioningBy(Dish::isVegetarian,
                        Collectors.groupingBy(Dish::getType)));
        System.out.println(vegetarianByType);

        //将数字按照质数、非质数分区
        Map<Boolean,List<Integer>> partitionPrimesMap=partitionPrimes(50);
        System.out.println(partitionPrimesMap);

    }

    public static boolean isPrime(int candidate){
        int candidateRoot=(int)Math.sqrt(candidate);
        return IntStream.rangeClosed(2,candidateRoot).noneMatch(i->candidate%i==0);
    }

    public static Map<Boolean,List<Integer>> partitionPrimes(int n){

        return IntStream.rangeClosed(2,n).boxed()
                .collect(Collectors.partitioningBy(Partitioning::isPrime));
    }
}
